package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员服务
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    // 根据手机号码查询
    @Override
    public Member findByTelephone(String telephone) {

        return memberDao.findByTelephone(telephone);
    }

    /**
     * 保存上月会员数到 t_monthmembernums 表
     * @param month
     * @param count
     */
    @Override
    public void saveCurrentMonthMemberCount(String month, Integer count) {
        memberDao.saveCurrentMonthMemberCount(month,count);
    }

    /**
     * 根据月份查询上月会员数
     * @param month
     * @return
     */
    @Override
    public Integer findMemberCountByMonth(String month) {
        String date = month+"-31";

        return memberDao.findMemberCountBeforeDate(date);
    }

    /**
     *  根据月份查询会员数
     * @param months
     * @return
     */
    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> list = new ArrayList<>();
        for (String month : months) {
            Integer count = memberDao.findMemberCountBeforeDate(month);
            list.add(count);
        }
        return list;
    }

    // 添加会员
    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null){
            // 使用MD5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }
}
